﻿// Fill out your copyright notice in the Description page of Project Settings.


#include "CharacterZD/BTTask/BTTask_AttackTarget.h"

#include "BehaviorTree/BlackboardComponent.h"
#include "BehaviorTree/BlackboardData.h"
#include "BehaviorTree/Blackboard/BlackboardKeyType_Object.h"
#include "CharacterZD/Core/MonsterAIController.h"
#include "CharacterZD/Core/RuleCharacterZD.h"

EBTNodeResult::Type UBTTask_AttackTarget::ExecuteTask(UBehaviorTreeComponent& OwnerComp, uint8* NodeMemory)
{
	Super::ExecuteTask(OwnerComp, NodeMemory);

	AMonsterAIController* MyAIController = Cast<AMonsterAIController>(OwnerComp.GetOwner());
	const UBlackboardComponent* MyBlackBoard = OwnerComp.GetBlackboardComponent();

	if (Blackboard_Actor.SelectedKeyType == UBlackboardKeyType_Object::StaticClass())
	{
		UObject* MyObject = MyBlackBoard->GetValueAsObject(Blackboard_Actor.SelectedKeyName);
		ARuleCharacterZD* TargetTower = Cast<ARuleCharacterZD>(MyObject);
		ARuleCharacterZD* MyPawn = Cast<ARuleCharacterZD>(MyAIController->GetPawn());

		if (TargetTower && MyPawn)
		{
			MyPawn->bAttack = true;
			MyAIController->AttackTarget(TargetTower);
			return EBTNodeResult::Succeeded;
		}
	
		MyPawn->bAttack = false;
		return EBTNodeResult::Succeeded;
	}
	
	return EBTNodeResult::Failed;
}

void UBTTask_AttackTarget::InitializeFromAsset(UBehaviorTree& Asset)
{
	Super::InitializeFromAsset(Asset);

	if (UBlackboardData* BBAsset = GetBlackboardAsset())
	{
		Blackboard_Actor.ResolveSelectedKey(*BBAsset);
	}
	else
	{
		UE_LOG(LogBehaviorTree, Warning, TEXT("Can 'Initialize' task:%s"), *GetName());
	}
}

void UBTTask_AttackTarget::OnGameplayTaskInitialized(UGameplayTask& Task)
{
	Super::OnGameplayTaskInitialized(Task);
}

void UBTTask_AttackTarget::OnGameplayTaskActivated(UGameplayTask& Task)
{
	Super::OnGameplayTaskActivated(Task);
}

void UBTTask_AttackTarget::OnGameplayTaskDeactivated(UGameplayTask& Task)
{
	Super::OnGameplayTaskDeactivated(Task);
}
